package com.example.home.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.example.home.databinding.ItemHomeBinding
import com.example.home.entity.HomeListEntity
import com.example.image.glide.GlideImgLoader

class HomeAdapter(private val data:List<HomeListEntity>):RecyclerView.Adapter<HomeAdapter.HomeViewHolder>() {
    private var itemOnClickListener:ItemOnClickListener? = null

    fun setItemOnClickListener(listener:ItemOnClickListener){
        this.itemOnClickListener = listener
    }
    inner class HomeViewHolder(val itemDataBinding:ItemHomeBinding):RecyclerView.ViewHolder(itemDataBinding.root)
    //创建ViewHolder
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HomeViewHolder {
        return HomeViewHolder(ItemHomeBinding.inflate(LayoutInflater.from(parent.context),parent,false))
    }

    override fun getItemCount(): Int = data.size
    //绑定数据
    override fun onBindViewHolder(holder: HomeViewHolder, position: Int) {
        val entity = data[position]
        //方法一:使用DataBinding给UI组件绑定数据
//        holder.itemDataBinding.entity = entity
//        holder.itemDataBinding.executePendingBindings()
        //方法二:传统方式
        holder.itemDataBinding.tvServiceName.text = entity.name
       // GlideImgLoader.loadResImage(holder.itemView,entity.image,holder.itemDataBinding.ivServiceIcon)
        Glide.with(holder.itemView)
            .load(entity.image)
            .skipMemoryCache(true) // 跳过内存缓存
            .diskCacheStrategy(DiskCacheStrategy.NONE) // 跳过磁盘缓存
            .into(holder.itemDataBinding.ivServiceIcon)
        //设置点击事件
        holder.itemDataBinding.root.setOnClickListener {
            itemOnClickListener?.onClick(it,position)
        }
    }
    interface ItemOnClickListener{
        fun onClick(view:View,position: Int)
    }
}